<?php

namespace app\service;

use Qcloud\Cos\Client;
use think\Validate;
use think\facade\Env;

class CosService
{
    protected $cosClient;
    protected $config;

    public function __construct()
    {
        $cosConfig = config('cos');
        $this->config = $cosConfig;

        $this->cosClient = new Client([
            'region' => $cosConfig['region'],
            'credentials' => [
                'secretId' => $cosConfig['secret_id'],
                'secretKey' => $cosConfig['secret_key']
            ],
            'bucket' => $cosConfig['bucket'],
            'scheme' => 'http',
            'verify' => false,
        ]);

        // $this->config = [
        //     'region' => Env::get('COS_REGION'),
        //     'credentials' => [
        //         'secretId' => Env::get('COS_SECRET_ID'),
        //         'secretKey' => Env::get('COS_SECRET_KEY'),
        //     ],
        //     'bucket' => Env::get('COS_BUCKET'),
        //     'scheme' => 'http',
        //     'verify' => false,
        // ];
        // $this->cosClient = new Client($this->config);
    }

    // 上传图片
    public function uploadImage($file)
    {

        try {
            // 验证文件
            // $validate = Validate([
            //     'file' => [
            //         'fileSize' => 10 * 1024 * 1024,
            //         'fileExt' => 'jpg,jpeg,png'
            //     ]
            // ]);
            // if (!$validate->check(['file' => $file])) {
            //     throw new \Exception('文件不符合要求：' . implode(', ', $validate->getError()));
            // }


            // 生成文件名
            $key = 'campus/images/' . date('ymd') . '/' . uniqid() . '.' . $file->getOriginalExtension();

            // 上传文件
            $this->cosClient->putObject([
                'Bucket' => $this->config['bucket'],
                'Region' => $this->config['region'],
                'Key' => $key,
                'Body' => fopen($file->getRealPath(), 'rb') // 上传流文件
            ]);

            // 返回文件的 URL
            return 'https://' . $this->config['bucket'] . '.cos.' . $this->config['region'] . '.myqcloud.com/' . $key;
        } catch (\Throwable $th) {
            return error('上传失败：' . $th->getMessage());
        }
    }

    // 批量上传图片
    public function uploadMultipleImages($files)
    {
        try {
            $urls = [];
            foreach ($files as $file) {
                $urls[] = $this->uploadImage($file);
            }
            return $urls;
        } catch (\Throwable $th) {
            throw new \Exception('批量上传失败：' . $th->getMessage());
        }
    }

    // 删除单张图片
    public function deleteImage($url)
    {
        try {
            // 从URL中提取Key
            $parsedUrl = parse_url($url);
            $key = ltrim($parsedUrl['path'], '/');

            // 删除文件
            $this->cosClient->deleteObject([
                'Bucket' => $this->config['bucket'],
                'Key' => $key
            ]);
            return true;
        } catch (\Throwable $th) {
            return error('删除失败：' . $th->getMessage());
        }
    }
}
